import logging

from poker_bot.core.models.dto.withdraw import WithdrawDTO, WithdrawWithDetailsDTO
from poker_bot.core.models.enums.withdraw import WithdrawStatus
from poker_bot.database.uow import SQLAlchemyUoW
from poker_bot.domain.user import UserEntity
from poker_bot.domain.withdraw import WithdrawEntity

logger = logging.getLogger(__name__)


class WithdrawService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def get_withdraw_by_id(
        self, withdraw_id: int
    ) -> WithdrawWithDetailsDTO | None:
        """Получаем запрос на вывод по id"""

        return await self._uow.withdraw_reader.get_withdraw_by_id(withdraw_id)

    async def get_all_withdrawals(
        self,
    ) -> list[WithdrawWithDetailsDTO]:
        return await self._uow.withdraw_reader.get_all_withdrawals()

    async def get_withdrawals_for_confirmation(
        self,
    ) -> list[WithdrawWithDetailsDTO]:
        """Получаем запросы на вывод для подтверждения"""

        return await self._uow.withdraw_reader.get_withdrawals_for_confirmation()

    async def update_withdraw_status(
        self, withdraw_id: int, status: WithdrawStatus
    ) -> None:
        withdraw: WithdrawEntity = await self._uow.withdraw_repo.acquire_withdraw_by_id(
            withdraw_id
        )
        withdraw.update_status(status)

        await self._uow.withdraw_repo.update_withdraw(withdraw)

        await self._uow.commit()

    async def create_withdraw(
        self, user_tg_id: int, payment_address: str, summ: float, payment_method_id: int
    ) -> WithdrawEntity:
        """Создаем запрос на вывод"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        withdraw = WithdrawEntity.create(
            user_id=user.id,
            payment_address=payment_address,
            summ=summ,
            payment_method_id=payment_method_id,
        )
        try:
            withdraw = await self._uow.withdraw_repo.create_withdraw(withdraw)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        return withdraw
